// API基础配置
const API_BASE_URL = 'http://localhost:5000'

// HTTP请求工具类
class HttpClient {
  constructor(baseURL = API_BASE_URL) {
    this.baseURL = baseURL
    this.token = uni.getStorageSync('token')
  }

  // 设置token
  setToken(token) {
    this.token = token
    if (token) {
      uni.setStorageSync('token', token)
    } else {
      uni.removeStorageSync('token')
    }
  }

  // 获取用户ID
  getUserId() {
    try {
      // 从storage获取用户信息
      const userInfo = uni.getStorageSync('userInfo')
      if (userInfo) {
        const parsed = typeof userInfo === 'string' ? JSON.parse(userInfo) : userInfo
        return parsed.id || null
      }
      return null
    } catch (e) {
      console.warn('获取用户信息失败:', e)
      return null
    }
  }

  // 获取请求头
  getHeaders() {
    const headers = {
      'Content-Type': 'application/json'
    }
    
    // 每次都从storage获取最新的token
    const currentToken = uni.getStorageSync('token')
    if (currentToken) {
      headers.Authorization = `Bearer ${currentToken}`
    }
    
    return headers
  }

  // 处理uni.request响应
  handleUniResponse(res) {
    if (res.statusCode >= 200 && res.statusCode < 300) {
      return res.data
    } else {
      const error = new Error(res.data?.message || `HTTP ${res.statusCode}`)
      error.status = res.statusCode
      error.response = { data: res.data }
      throw error
    }
  }

  // GET请求
  async get(url) {
    return new Promise((resolve, reject) => {
      uni.request({
        url: `${this.baseURL}${url}`,
        method: 'GET',
        header: this.getHeaders(),
        success: (res) => {
          try {
            resolve(this.handleUniResponse(res))
          } catch (error) {
            reject(error)
          }
        },
        fail: reject
      })
    })
  }

  // POST请求
  async post(url, data = null) {
    return new Promise((resolve, reject) => {
      const requestOptions = {
        url: `${this.baseURL}${url}`,
        method: 'POST',
        header: this.getHeaders()
      }
      
      // 只有当data不为null时才设置data
      if (data !== null && data !== undefined) {
        requestOptions.data = data
      }
      
      uni.request({
        ...requestOptions,
        success: (res) => {
          try {
            resolve(this.handleUniResponse(res))
          } catch (error) {
            reject(error)
          }
        },
        fail: reject
      })
    })
  }

  // PUT请求
  async put(url, data) {
    return new Promise((resolve, reject) => {
      uni.request({
        url: `${this.baseURL}${url}`,
        method: 'PUT',
        header: this.getHeaders(),
        data: data,
        success: (res) => {
          try {
            resolve(this.handleUniResponse(res))
          } catch (error) {
            reject(error)
          }
        },
        fail: reject
      })
    })
  }

  // DELETE请求
  async delete(url) {
    return new Promise((resolve, reject) => {
      uni.request({
        url: `${this.baseURL}${url}`,
        method: 'DELETE',
        header: this.getHeaders(),
        success: (res) => {
          try {
            resolve(this.handleUniResponse(res))
          } catch (error) {
            reject(error)
          }
        },
        fail: reject
      })
    })
  }

  // 文件上传请求
  async upload(url, data) {
    const headers = {}
    if (this.token) {
      headers.Authorization = `Bearer ${this.token}`
    }
    
    // 获取用户ID
    const userId = this.getUserId()
    
    if (!userId) {
      console.error('用户未登录或用户ID不存在')
      throw new Error('请先登录后再上传文档')
    }
    
    headers['X-User-Id'] = userId

    return new Promise((resolve, reject) => {
      uni.uploadFile({
        url: `${this.baseURL}${url}`,
        header: headers,
        formData: data,
        success: (res) => {
          try {
            const data = JSON.parse(res.data)
            resolve(data)
          } catch (error) {
            reject(error)
          }
        },
        fail: reject
      })
    })
  }
}

export default new HttpClient()
